Extracting essential data from a dataset and displaying it is a necessary part of data science; therefore individuals can make correct decisions based on the data. In this assignment, you will extract some stock data, you will then display this data in a graph.
Estimated Time Needed: 30 min
*Note*:- If you are working in IBM Cloud Watson Studio, please replace the command for installing nbformat from !pip install nbformat==4.2.0 to simply !pip install nbformat
!pip install yfinance==0.1.67
!mamba install bs4==4.10.0 -y
!pip install nbformat==4.2.0
Collecting yfinance==0.1.67
Downloading yfinance-0.1.67-py2.py3-none-any.whl (25 kB)
Requirement already satisfied: pandas>=0.24 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from yfinance==0.1.67) (1.3.5)
Requirement already satisfied: numpy>=1.15 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from yfinance==0.1.67) (1.21.6)
Requirement already satisfied: requests>=2.20 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from yfinance==0.1.67) (2.29.0)
Requirement already satisfied: multitasking>=0.0.7 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from yfinance==0.1.67) (0.0.11)
Requirement already satisfied: lxml>=4.5.1 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from yfinance==0.1.67) (4.9.2)
Requirement already satisfied: python-dateutil>=2.7.3 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from pandas>=0.24->yfinance==0.1.67) (2.8.2)
Requirement already satisfied: pytz>=2017.3 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from pandas>=0.24->yfinance==0.1.67) (2023.3)
Requirement already satisfied: charset-normalizer<4,>=2 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from requests>=2.20->yfinance==0.1.67) (3.1.0)
Requirement already satisfied: idna<4,>=2.5 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from requests>=2.20->yfinance==0.1.67) (3.4)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from requests>=2.20->yfinance==0.1.67) (1.26.15)
Requirement already satisfied: certifi>=2017.4.17 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from requests>=2.20->yfinance==0.1.67) (2023.5.7)
Requirement already satisfied: six>=1.5 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from python-dateutil>=2.7.3->pandas>=0.24->yfinance==0.1.67) (1.16.0)
Installing collected packages: yfinance
Attempting uninstall: yfinance
Found existing installation: yfinance 0.2.4
Uninstalling yfinance-0.2.4:
Successfully uninstalled yfinance-0.2.4
Successfully installed yfinance-0.1.67
__ __ __ __
/ \ / \ / \ / \
/ \/ \/ \/ \
███████████████/ /██/ /██/ /██/ /████████████████████████
/ / \ / \ / \ / \ \____
/ / \_/ \_/ \_/ \ o \__,
/ _/ \_____/ `
|/
███╗ ███╗ █████╗ ███╗ ███╗██████╗ █████╗
████╗ ████║██╔══██╗████╗ ████║██╔══██╗██╔══██╗
██╔████╔██║███████║██╔████╔██║██████╔╝███████║
██║╚██╔╝██║██╔══██║██║╚██╔╝██║██╔══██╗██╔══██║
██║ ╚═╝ ██║██║ ██║██║ ╚═╝ ██║██████╔╝██║ ██║
╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝
mamba (1.4.2) supported by @QuantStack
GitHub: https://github.com/mamba-org/mamba
Twitter: https://twitter.com/QuantStack
█████████████████████████████████████████████████████████████
Looking for: ['bs4==4.10.0']
[+] 0.0s
pkgs/main/linux-64 ━━━━━━━╸━━━━━━━━━━━━━━━━━ 0.0 B / ??.?MB @ ??.?MB/s 0.0s[+] 0.1s
pkgs/main/linux-64 ━━━━━━━╸━━━━━━━━━━━━━━━━━ 0.0 B / ??.?MB @ ??.?MB/s 0.1s
pkgs/main/noarch ━━━━━━━━╸━━━━━━━━━━━━━━━━ 0.0 B / ??.?MB @ ??.?MB/s 0.1s
pkgs/r/linux-64 ╸━━━━━━━━━━━━━━━╸━━━━━━━━ 0.0 B / ??.?MB @ ??.?MB/s 0.1s
pkgs/r/noarch ━━━━━━━━━╸━━━━━━━━━━━━━━━ 0.0 B / ??.?MB @ ??.?MB/s 0.1s[+] 0.2s
pkgs/main/linux-64 ━━━━━━━━━╸━━━━━━━━━━━━━━━ 16.4kB / ??.?MB @ 107.2kB/s 0.2s
pkgs/main/noarch ━━━━━━━━━━╸━━━━━━━━━━━━━━ 86.0kB / ??.?MB @ 562.0kB/s 0.2s
pkgs/r/linux-64 ━━━╸━━━━━━━━━━━━━━━╸━━━━━ 57.4kB / ??.?MB @ 374.0kB/s 0.2s
pkgs/r/noarch ━━━━━━━━━━━╸━━━━━━━━━━━━━ 73.7kB / ??.?MB @ 479.8kB/s 0.2s[+] 0.3s
pkgs/main/linux-64 ━━━━━━━━━━━━╸━━━━━━━━━━━ 516.1kB @ 2.0MB/s 0.3s
pkgs/main/noarch ━━━━━━━━━━━━━━━━━━━━━━━━ 852.1kB @ 2.9MB/s Finalizing 0.3s
pkgs/r/linux-64 ━━━━╸━━━━━━━━━━━━━━━╸━━━ 610.3kB @ 2.4MB/s 0.3s
pkgs/r/noarch ━━━━━━━━━━━━━╸━━━━━━━━━━ 622.6kB @ 2.4MB/s 0.3spkgs/main/noarch @ 2.9MB/s 0.3s
[+] 0.4s
pkgs/main/linux-64 ━━━━━━━━━━━━━━╸━━━━━━━━━ 1.1MB @ 3.1MB/s 0.4s
pkgs/r/linux-64 ━━━━━━━╸━━━━━━━━━━━━━━━━ 1.2MB @ 3.3MB/s 0.4s
pkgs/r/noarch ━━━━━━━━━━━━━━━━━━━━━━━━ 1.3MB @ 3.4MB/s Finalizing 0.4spkgs/r/noarch @ 3.4MB/s 0.4s
pkgs/r/linux-64 @ 3.4MB/s 0.4s
[+] 0.5s
pkgs/main/linux-64 ━╸━━━━━━━━━━━━━━━╸━━━━━━━ 1.8MB / ??.?MB @ 3.7MB/s 0.5s[+] 0.6s
pkgs/main/linux-64 ━━━╸━━━━━━━━━━━━━━━╸━━━━━ 2.3MB / ??.?MB @ 4.0MB/s 0.6s[+] 0.7s
pkgs/main/linux-64 ━━━━━╸━━━━━━━━━━━━━━━╸━━━ 2.8MB / ??.?MB @ 4.2MB/s 0.7s[+] 0.8s
pkgs/main/linux-64 ━━━━━━━━╸━━━━━━━━━━━━━━━━ 3.3MB / ??.?MB @ 4.2MB/s 0.8s[+] 0.9s
pkgs/main/linux-64 ━━━━━━━━━━╸━━━━━━━━━━━━━━ 3.9MB / ??.?MB @ 4.4MB/s 0.9s[+] 1.0s
pkgs/main/linux-64 ━━━━━━━━━━━━━╸━━━━━━━━━━━ 4.4MB / ??.?MB @ 4.5MB/s 1.0s[+] 1.1s
pkgs/main/linux-64 ━━━━━━━╸━━━━━━━━━━━━━━━━━ 5.0MB / ??.?MB @ 4.6MB/s 1.1s[+] 1.2s
pkgs/main/linux-64 ━━━━━━━━━╸━━━━━━━━━━━━━━━ 5.6MB / ??.?MB @ 4.7MB/s 1.2s[+] 1.3s
pkgs/main/linux-64 ━━━━━━━━━━━╸━━━━━━━━━━━━━ 5.9MB / ??.?MB @ 4.7MB/s 1.3spkgs/main/linux-64 6.0MB @ 4.8MB/s 1.4s
Pinned packages:
- python 3.7.*
Transaction
Prefix: /home/jupyterlab/conda/envs/python
Updating specs:
- bs4==4.10.0
- ca-certificates
- certifi
- openssl
Package Version Build Channel Size
─────────────────────────────────────────────────────────────────────────────
Install:
─────────────────────────────────────────────────────────────────────────────
+ bs4 4.10.0 hd3eb1b0_0 pkgs/main/noarch 10kB
Upgrade:
─────────────────────────────────────────────────────────────────────────────
- ca-certificates 2023.5.7 hbcca054_0 conda-forge
+ ca-certificates 2023.05.30 h06a4308_0 pkgs/main/linux-64 123kB
- openssl 1.1.1t h0b41bf4_0 conda-forge
+ openssl 1.1.1v h7f8727e_0 pkgs/main/linux-64 4MB
Downgrade:
─────────────────────────────────────────────────────────────────────────────
- beautifulsoup4 4.11.1 pyha770c72_0 conda-forge
+ beautifulsoup4 4.10.0 pyh06a4308_0 pkgs/main/noarch 87kB
Summary:
Install: 1 packages
Upgrade: 2 packages
Downgrade: 1 packages
Total download: 4MB
─────────────────────────────────────────────────────────────────────────────
[+] 0.0s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 0.0 B 0.0s
Extracting ━━━━━━━━━━━━━━━━━━━━━━━ 0 0.0s[+] 0.1s
Downloading (4) ━━━━━━━━━━━━━━━━━━━━━━━ 0.0 B beautifulsoup4 0.0s
Extracting ━━━━━━━━━━━━━━━━━━━━━━━ 0 0.0sbeautifulsoup4 86.6kB @ 591.3kB/s 0.2s
ca-certificates 122.6kB @ 832.7kB/s 0.2s
bs4 10.2kB @ 67.9kB/s 0.2s
openssl 3.9MB @ 24.0MB/s 0.2s
[+] 0.2s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━╸━━━━━━━━━━━━━━━━ 0 beautifulsoup4 0.0s[+] 0.3s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━╸━━━━━━━━━━━━━━━ 0 beautifulsoup4 0.1s[+] 0.4s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━━╸━━━━━━━━━━━━━━ 0 beautifulsoup4 0.2s[+] 0.5s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━━━╸━━━━━━━━━━━━━ 0 beautifulsoup4 0.3s[+] 0.6s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━━━━╸━━━━━━━━━━━━ 0 bs4 0.4s[+] 0.7s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━━━━━╸━━━━━━━━━━━ 0 bs4 0.5s[+] 0.8s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━━━━━━━╸━━━━━━━━━ 0 bs4 0.6s[+] 0.9s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━━╸━━━━━━━━━━━━━━ 0 bs4 0.7s[+] 1.0s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━━━╸━━━━━━━━━━━━━ 0 ca-certificates 0.8s[+] 1.1s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━━━━╸━━━━━━━━━━━━ 0 ca-certificates 0.9s[+] 1.2s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━━━━━╸━━━━━━━━━━━ 0 ca-certificates 1.0s[+] 1.3s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━━━━━━╸━━━━━━━━━━ 0 ca-certificates 1.1s[+] 1.4s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━━━━━━━╸━━━━━━━━━ 0 openssl 1.2s[+] 1.5s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━━━━━━━━╸━━━━━━━━ 0 openssl 1.3s[+] 1.6s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ━━━━━━━━━━━━━━━╸━━━━━━━ 0 openssl 1.4s[+] 1.7s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (4) ╸━━━━━━━━━━━━━━━╸━━━━━━ 0 openssl 1.5s[+] 1.8s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (3) ━━━━╸━━━━━━━━━━━━━━━━━━ 1 beautifulsoup4 1.6s[+] 1.9s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (2) ━━━━━━━━━━╸━━━━━━━━━━━━ 2 beautifulsoup4 1.7s[+] 2.0s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (1) ━━━━━━━━━━━━━━━━╸━━━━━━ 3 beautifulsoup4 1.8s[+] 2.1s
Downloading ━━━━━━━━━━━━━━━━━━━━━━━ 4.1MB 0.1s
Extracting (1) ━━━━━━━━━━━━━━━━╸━━━━━━ 3 beautifulsoup4 1.9s
Downloading and Extracting Packages
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
Collecting nbformat==4.2.0
Downloading nbformat-4.2.0-py2.py3-none-any.whl (153 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 153.3/153.3 kB 26.0 MB/s eta 0:00:00
Requirement already satisfied: ipython-genutils in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from nbformat==4.2.0) (0.2.0)
Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from nbformat==4.2.0) (4.17.3)
Requirement already satisfied: jupyter-core in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from nbformat==4.2.0) (4.12.0)
Requirement already satisfied: traitlets>=4.1 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from nbformat==4.2.0) (5.9.0)
Requirement already satisfied: attrs>=17.4.0 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat==4.2.0) (23.1.0)
Requirement already satisfied: importlib-metadata in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat==4.2.0) (4.11.4)
Requirement already satisfied: importlib-resources>=1.4.0 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat==4.2.0) (5.12.0)
Requirement already satisfied: pkgutil-resolve-name>=1.3.10 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat==4.2.0) (1.3.10)
Requirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat==4.2.0) (0.19.3)
Requirement already satisfied: typing-extensions in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat==4.2.0) (4.5.0)
Requirement already satisfied: zipp>=3.1.0 in /home/jupyterlab/conda/envs/python/lib/python3.7/site-packages (from importlib-resources>=1.4.0->jsonschema!=2.5.0,>=2.4->nbformat==4.2.0) (3.15.0)
Installing collected packages: nbformat
Attempting uninstall: nbformat
Found existing installation: nbformat 5.8.0
Uninstalling nbformat-5.8.0:
Successfully uninstalled nbformat-5.8.0
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
jupyter-server 1.24.0 requires nbformat>=5.2.0, but you have nbformat 4.2.0 which is incompatible.
nbclient 0.7.4 requires nbformat>=5.1, but you have nbformat 4.2.0 which is incompatible.
nbconvert 7.4.0 requires nbformat>=5.1, but you have nbformat 4.2.0 which is incompatible.
Successfully installed nbformat-4.2.0
import yfinance as yf
import pandas as pd
import requests
from bs4 import BeautifulSoup
import plotly.graph_objects as go
from plotly.subplots import make_subplots
In this section, we define the function make_graph. You don't have to know how the function works, you should only care about the inputs. It takes a dataframe with stock data (dataframe must contain Date and Close columns), a dataframe with revenue data (dataframe must contain Date and Revenue columns), and the name of the stock.
def make_graph(stock_data, revenue_data, stock):
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=("Historical Share Price", "Historical Revenue"), vertical_spacing = .3)
stock_data_specific = stock_data[stock_data.Date <= '2021--06-14']
revenue_data_specific = revenue_data[revenue_data.Date <= '2021-04-30']
fig.add_trace(go.Scatter(x=pd.to_datetime(stock_data_specific.Date, infer_datetime_format=True), y=stock_data_specific.Close.astype("float"), name="Share Price"), row=1, col=1)
fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data_specific.Date, infer_datetime_format=True), y=revenue_data_specific.Revenue.astype("float"), name="Revenue"), row=2, col=1)
fig.update_xaxes(title_text="Date", row=1, col=1)
fig.update_xaxes(title_text="Date", row=2, col=1)
fig.update_yaxes(title_text="Price ($US)", row=1, col=1)
fig.update_yaxes(title_text="Revenue ($US Millions)", row=2, col=1)
fig.update_layout(showlegend=False,
height=900,
title=stock,
xaxis_rangeslider_visible=True)
fig.show()
Using the Ticker function enter the ticker symbol of the stock we want to extract data on to create a ticker object. The stock is Tesla and its ticker symbol is TSLA.
tesla = yf.Ticker("TSLA")
Using the ticker object and the function history extract stock information and save it in a dataframe named tesla_data. Set the period parameter to max so we get information for the maximum amount of time.
tesla_data = tesla.history(period='max')
Reset the index using the reset_index(inplace=True) function on the tesla_data DataFrame and display the first five rows of the tesla_data dataframe using the head function. Take a screenshot of the results and code from the beginning of Question 1 to the results below.
tesla_data.reset_index(inplace=True)
tesla_data.head(5)
| Date | Open | High | Low | Close | Volume | Dividends | Stock Splits | |
|---|---|---|---|---|---|---|---|---|
| 0 | 2010-06-29 | 1.266667 | 1.666667 | 1.169333 | 1.592667 | 281494500 | 0 | 0.0 |
| 1 | 2010-06-30 | 1.719333 | 2.028000 | 1.553333 | 1.588667 | 257806500 | 0 | 0.0 |
| 2 | 2010-07-01 | 1.666667 | 1.728000 | 1.351333 | 1.464000 | 123282000 | 0 | 0.0 |
| 3 | 2010-07-02 | 1.533333 | 1.540000 | 1.247333 | 1.280000 | 77097000 | 0 | 0.0 |
| 4 | 2010-07-06 | 1.333333 | 1.333333 | 1.055333 | 1.074000 | 103003500 | 0 | 0.0 |
Use the requests library to download the webpage https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/revenue.htm Save the text of the response as a variable named html_data.
import requests
# URL of the webpage to download
url = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/revenue.htm"
# Send a GET request to the URL
response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Save the HTML content as a variable named html_data
html_data = response.text
print("Webpage downloaded successfully.")
else:
print("Failed to download the webpage. Status code:", response.status_code)
Webpage downloaded successfully.
Parse the html data using beautiful_soup.
from bs4 import BeautifulSoup
# Assuming you already have 'html_data' containing the HTML content
# Create a BeautifulSoup object
soup = BeautifulSoup(html_data, 'html.parser')
# Now you can work with the parsed HTML, for example, let's print the title of the webpage:
title = soup.title
print("Title of the webpage:", title.text)
# You can navigate the HTML structure, extract elements, and perform various operations on it.
# For example, to find all <a> (anchor) tags:
all_links = soup.find_all('a')
for link in all_links:
print("Link Text:", link.text)
print("Link URL:", link.get('href'))
Title of the webpage: Tesla Revenue 2010-2022 | TSLA | MacroTrends Link Text: Link URL: https://www.macrotrends.net Link Text: Stock Screener Link URL: /stocks/stock-screener Link Text: Stock Research Link URL: /stocks/research Link Text: Market Indexes Link URL: /charts/stock-indexes Link Text: Precious Metals Link URL: /charts/precious-metals Link Text: Energy Link URL: /charts/energy Link Text: Commodities Link URL: /charts/commodities Link Text: Exchange Rates Link URL: /charts/exchange-rates Link Text: Interest Rates Link URL: /charts/interest-rates Link Text: Economy Link URL: /charts/economy Link Text: Global Metrics Link URL: /countries/topic-overview Link Text: Prices Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/stock-price-history Link Text: Financials Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/financial-statements Link Text: Revenue & Profit Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue Link Text: Assets & Liabilities Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/total-assets Link Text: Margins Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/profit-margins Link Text: Price Ratios Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/pe-ratio Link Text: Other Ratios Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/current-ratio Link Text: Other Metrics Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/dividend-yield-history Link Text: Revenue Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue Link Text: Gross Profit Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/gross-profit Link Text: Operating Income Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/operating-income Link Text: EBITDA Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/ebitda Link Text: Net Income Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/net-income Link Text: EPS Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/eps-earnings-per-share-diluted Link Text: Shares Outstanding Link URL: https://www.macrotrends.net/stocks/charts/TSLA/tesla/shares-outstanding Link Text: Auto/Tires/Trucks Link URL: https://www.macrotrends.net/stocks/sector/5/auto-tires-trucks Link Text: Auto Manufacturers - Domestic Link URL: https://www.macrotrends.net/stocks/industry/7/ Link Text: General Motors (GM) Link URL: /stocks/charts/GM/general-motors/revenue Link Text: Ford Motor (F) Link URL: /stocks/charts/F/ford-motor/revenue Link Text: Harley-Davidson (HOG) Link URL: /stocks/charts/HOG/harley-davidson/revenue Link Text: Polaris (PII) Link URL: /stocks/charts/PII/polaris/revenue Link Text: IAA (IAA) Link URL: /stocks/charts/IAA/iaa/revenue Link Text: Fisker (FSR) Link URL: /stocks/charts/FSR/fisker/revenue Link Text: Lion Electric (LEV) Link URL: /stocks/charts/LEV/lion-electric/revenue Link Text: Volta (VLTA) Link URL: /stocks/charts/VLTA/volta/revenue Link Text: Bird Global (BRDS) Link URL: /stocks/charts/BRDS/bird-global/revenue Link Text: Lightning EMotors (ZEV) Link URL: /stocks/charts/ZEV/lightning-emotors/revenue Link Text: Terms of Service Link URL: /terms Link Text: Privacy Policy Link URL: /privacy Link Text: Contact Us Link URL: mailto:%69n%66o@%6Dac%72otrends%2En%65t Link Text: Do Not Sell My Personal Information Link URL: /ccpa Link Text: Zacks Investment Research, Inc. Link URL: https://www.zacksdata.com Link Text: Tesla Revenue 2010-2022 | TSLA Link URL: None Link Text: Macrotrends Link URL: None Link Text: Source Link URL: None Link Text: Tesla Revenue 2010-2022 | TSLA Link URL: None Link Text: Macrotrends Link URL: None Link Text: Source Link URL: None
Using BeautifulSoup or the read_html function extract the table with Tesla Revenue and store it into a dataframe named tesla_revenue. The dataframe should have columns Date and Revenue.
Below is the code to isolate the table, you will now need to loop through the rows and columns like in the previous lab
soup.find_all("tbody")[1]
If you want to use the read_html function the table is located at index 1
# Locate the table with Tesla Revenue using the specific code
table = soup.find_all("tbody")[1]
# Initialize empty lists to store data
dates = []
revenues = []
# Loop through the rows of the table
for row in table.find_all("tr"):
# Extract the columns (cells) from each row
cols = row.find_all("td")
if len(cols) == 2:
date = cols[0].text.strip()
revenue = cols[1].text.strip()
# Append data to lists
dates.append(date)
revenues.append(revenue)
# Create a DataFrame from the lists
tesla_revenue = pd.DataFrame({'Date': dates, 'Revenue': revenues})
Execute the following line to remove the comma and dollar sign from the Revenue column.
tesla_revenue["Revenue"] = tesla_revenue['Revenue'].str.replace(',|\$',"")
/home/jupyterlab/conda/envs/python/lib/python3.7/site-packages/ipykernel_launcher.py:1: FutureWarning: The default value of regex will change from True to False in a future version. """Entry point for launching an IPython kernel.
Execute the following lines to remove an null or empty strings in the Revenue column.
tesla_revenue.dropna(inplace=True)
tesla_revenue = tesla_revenue[tesla_revenue['Revenue'] != ""]
Display the last 5 row of the tesla_revenue dataframe using the tail function. Take a screenshot of the results.
tesla_revenue.tail(5)
| Date | Revenue | |
|---|---|---|
| 48 | 2010-09-30 | 31 |
| 49 | 2010-06-30 | 28 |
| 50 | 2010-03-31 | 21 |
| 52 | 2009-09-30 | 46 |
| 53 | 2009-06-30 | 27 |
Using the Ticker function enter the ticker symbol of the stock we want to extract data on to create a ticker object. The stock is GameStop and its ticker symbol is GME.
gamestop = yf.Ticker('GME')
Using the ticker object and the function history extract stock information and save it in a dataframe named gme_data. Set the period parameter to max so we get information for the maximum amount of time.
gme_data = gamestop.history(period='max')
Reset the index using the reset_index(inplace=True) function on the gme_data DataFrame and display the first five rows of the gme_data dataframe using the head function. Take a screenshot of the results and code from the beginning of Question 3 to the results below.
gme_data.reset_index(inplace=True)
gme_data.head(5)
| Date | Open | High | Low | Close | Volume | Dividends | Stock Splits | |
|---|---|---|---|---|---|---|---|---|
| 0 | 2002-02-13 | 1.620129 | 1.693350 | 1.603296 | 1.691667 | 76216000 | 0.0 | 0.0 |
| 1 | 2002-02-14 | 1.712707 | 1.716073 | 1.670625 | 1.683250 | 11021600 | 0.0 | 0.0 |
| 2 | 2002-02-15 | 1.683251 | 1.687459 | 1.658002 | 1.674834 | 8389600 | 0.0 | 0.0 |
| 3 | 2002-02-19 | 1.666418 | 1.666418 | 1.578047 | 1.607504 | 7410400 | 0.0 | 0.0 |
| 4 | 2002-02-20 | 1.615920 | 1.662210 | 1.603296 | 1.662210 | 6892800 | 0.0 | 0.0 |
Use the requests library to download the webpage https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/stock.html. Save the text of the response as a variable named html_data.
import requests
# URL of the webpage to download
url = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/stock.html"
# Send a GET request to the URL
response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Save the HTML content as a variable named html_data
html_data = response.text
print("Webpage downloaded successfully.")
else:
print("Failed to download the webpage. Status code:", response.status_code)
Webpage downloaded successfully.
Parse the html data using beautiful_soup.
# Parse the HTML content using BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
# Now you can work with the parsed HTML content as needed
# For example, you can print the title of the webpage:
title = soup.title
print("Title of the webpage:", title.text)
# Or you can find specific elements in the HTML using their tags, attributes, or other criteria:
# Example: Find all <a> (anchor) tags
all_links = soup.find_all('a')
for link in all_links:
print("Link Text:", link.text)
print("Link URL:", link.get('href'))
Title of the webpage: GameStop Revenue 2006-2020 | GME | MacroTrends Link Text: Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/ Link Text: Stock Screener Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/stock-screener Link Text: Stock Research Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/research Link Text: Market Indexes Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/charts/stock-indexes Link Text: Precious Metals Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/charts/precious-metals Link Text: Energy Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/charts/energy Link Text: Commodities Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/charts/commodities Link Text: Exchange Rates Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/charts/exchange-rates Link Text: Interest Rates Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/charts/interest-rates Link Text: Futures Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/futures Link Text: Economy Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/charts/economy Link Text: Global Metrics Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/countries/topic-overview Link Text: Prices Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/stock-price-history Link Text: Financials Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/financial-statements Link Text: Revenue & Profit Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/revenue Link Text: Assets & Liabilities Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/total-assets Link Text: Margins Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/profit-margins Link Text: Price Ratios Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/pe-ratio Link Text: Other Ratios Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/current-ratio Link Text: Other Metrics Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/dividend-yield-history Link Text: Revenue Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/revenue Link Text: Gross Profit Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/gross-profit Link Text: Operating Income Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/operating-income Link Text: EBITDA Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/ebitda Link Text: Net Income Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/net-income Link Text: EPS Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/eps-earnings-per-share-diluted Link Text: Shares Outstanding Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GME/gamestop/shares-outstanding Link Text: Retail/Wholesale Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/sector/3/retail-wholesale Link Text: Retail - Consumer Electronics Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/industry/156/ Link Text: Best Buy (BBY) Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/BBY/best-buy/revenue Link Text: Aaron's, (AAN) Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/AAN/aarons,-/revenue Link Text: GOME Retail Holdings (GMELY) Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/GMELY/gome-retail-holdings/revenue Link Text: Systemax (SYX) Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/SYX/systemax/revenue Link Text: Conn's (CONN) Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/CONN/conns/revenue Link Text: Taitron Components (TAIT) Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/stocks/charts/TAIT/taitron-components/revenue Link Text: Terms of Service Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/terms Link Text: Privacy Policy Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/privacy Link Text: Contact Us Link URL: https://web.archive.org/web/20200814131437/mailto:info@macrotrends.net Link Text: Do Not Sell My Personal Information Link URL: https://web.archive.org/web/20200814131437/https://www.macrotrends.net/ccpa Link Text: Zacks Investment Research, Inc. Link URL: https://web.archive.org/web/20200814131437/https://www.zacksdata.com/ Link Text: GameStop Revenue 2006-2020 | GME Link URL: None Link Text: Macrotrends Link URL: None Link Text: Source Link URL: None Link Text: GameStop Revenue 2006-2020 | GME Link URL: None Link Text: Macrotrends Link URL: None Link Text: Source Link URL: None
gme_revenueUsing BeautifulSoup or the read_html function extract the table with GameStop Revenue and store it into a dataframe named gme_revenue. The dataframe should have columns Date and Revenue. Make sure the comma and dollar sign is removed from the Revenue column using a method similar to what you did in Question 2.
Below is the code to isolate the table, you will now need to loop through the rows and columns like in the previous lab
soup.find_all("tbody")[1]
If you want to use the read_html function the table is located at index 1
# Locate the table with GameStop Revenue using the specific code
table = soup.find_all("tbody")[1]
# Initialize empty lists to store data
dates = []
revenues = []
# Loop through the rows of the table
for row in table.find_all("tr"):
# Extract the columns (cells) from each row
cols = row.find_all("td")
if len(cols) == 2:
date = cols[0].text.strip()
revenue = cols[1].text.strip()
# Append data to lists
dates.append(date)
revenues.append(revenue)
# Create a DataFrame from the lists
gme_revenue = pd.DataFrame({'Date': dates, 'Revenue': revenues})
gme_revenue["Revenue"] = gme_revenue['Revenue'].str.replace(',|\$',"")
/home/jupyterlab/conda/envs/python/lib/python3.7/site-packages/ipykernel_launcher.py:1: FutureWarning: The default value of regex will change from True to False in a future version.
gme_revenue.dropna(inplace=True)
gme_revenue = gme_revenue[gme_revenue['Revenue'] != ""]
Display the last five rows of the gme_revenue dataframe using the tail function. Take a screenshot of the results.
gme_revenue.tail(5)
| Date | Revenue | |
|---|---|---|
| 57 | 2006-01-31 | 1667 |
| 58 | 2005-10-31 | 534 |
| 59 | 2005-07-31 | 416 |
| 60 | 2005-04-30 | 475 |
| 61 | 2005-01-31 | 709 |
Use the make_graph function to graph the Tesla Stock Data, also provide a title for the graph. The structure to call the make_graph function is make_graph(tesla_data, tesla_revenue, 'Tesla'). Note the graph will only show data upto June 2021.
make_graph(tesla_data, tesla_revenue, 'Tesla')
Use the make_graph function to graph the GameStop Stock Data, also provide a title for the graph. The structure to call the make_graph function is make_graph(gme_data, gme_revenue, 'GameStop'). Note the graph will only show data upto June 2021.
make_graph(gme_data, gme_revenue, 'GameStop')
Joseph Santarcangelo has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.
Azim Hirjani
| Date (YYYY-MM-DD) | Version | Changed By | Change Description |
|---|---|---|---|
| 2022-02-28 | 1.2 | Lakshmi Holla | Changed the URL of GameStop |
| 2020-11-10 | 1.1 | Malika Singla | Deleted the Optional part |
| 2020-08-27 | 1.0 | Malika Singla | Added lab to GitLab |